/**
 * date:2020/02/27
 * author:Mr.Chung
 * version:2.0
 * description:layuimini 主体框架扩展
 */
layui.define(["jquery", "miniMenu", "element", "miniTab", "miniTheme"], function (exports) {
    var $ = layui.$,
        layer = layui.layer,
        miniMenu = layui.miniMenu,
        miniTheme = layui.miniTheme,
        element = layui.element,
        miniTab = layui.miniTab;

    if (!/http(s*):\/\//.test(location.href)) {
        var tips = "请先将项目部署至web容器（Apache/Tomcat/Nginx/IIS/等），否则部分数据将无法显示";
        return layer.alert(tips);
    }



    let {
        //QD
        GetWebApiInfo,
        GetFormDataApiInfo,
        GetFormDataCondition,
        QDFitlerToEj2,
        Ej2ToQDFilter,
        QDFilterToEj2Rule,
        Ej2RuleToQDFilter,
        Ej2PredicateToEj2Rule,
        GetFormDataOrder,
        GetRequestTableObj,
        SetChildTableFilterValue,
        SetTableFilterValue,
        GetDataManagerObj,
        GetDataManagerByDataTable,
        GetTableRequestComplete,
        GetDataByDataTable,
        ExecRequest,
        Adaptor,
        //QC
        SysLogin,
        LoginOut,
        RecordMyUserInfo,
        isEmptyObject,
        StringTrim,
        GetNewGUID,
        GetQueryString,
        ReturnPortalCenter,
        GetFormFilePath,
        GridAutoSize,
        EditScreenShotPage,
        //comm
        CheckboxList,
        ALink,
        QYCardView,
        QYIconSelector,
        BindFormCtrl,
        LayoutGroupBind,
        CascadingChildCtrl,
        QYCtrlBind,
        UploadPopupExt,
        UploadSetCustomPath,
        ToSelectFilesAction,
        SysUploadFileSelected,
        FileUpload,
        FileDelete,
        FileDownload,
        CreateFolder,
        FileCopy,
        FileMove,
        FileRename,
        FileView,
        //pagebind
        FormInit,
        GetFormDataApiUrl,
        GetGridColumnEditParam,
        SysSelectDataBind,
        GridBind,
        CtrlBind,
        LocaDataBind,
        SetFromDataCurrentRow,
        SetFromDataCurrentRowBayKeyValue,
        SetFromDataSelectRow,
        SetFromDataSelectRowByKeyValue,
        GetFormChildDataObj,
        SaveAllData,
        BatchSave,
        SysAppend,
        ReplaceDisplayClass,
        GetFormFunData,
        GetUserShowFun,
        GetUserEditFun,
        SetGridFun,
        GridRowSelecting,
        GridQueryCellInfo,
        GridBeforeBatchAdd,
        GridBeginEdit,
        ValidateData,
        CreateSysGridToolbarTemp,
        GridImportFile,
        GetGridImportParam,
        ShowTempEditPopup,
        HideTempEditPopup,
        SetTreeViewSelectNode,
        StartFlow,
        RevokeFlow,
        ReturnFlow,
        EndFlow,
        AddFlowReceiveUser,
        GetFlowCandidate,
        GetDataSource,
        OpenIconLibrary,
        //ctrl
        PanelExt,
        GridViewExt,
        FormLayoutExt,
        QYLabel,
        QYSpinEdit,
        QYColorEdit,
        QYPopup,
        QYTabGroup,
        QYBadge,
        QYCustomFilter,
        QYFileView,
        QYFileManager,
        replaceIllegalCharactersWithFullWidth,
        BtnTextBoxColumnTempExt,
        CheckBoxListTempExt,
        ColorEditColumnTempExt,
        SpinEditColumnTempExt,
        DropDownTreeColumnTempExt,
        HyperLinkColumnTempExt,
        ImageColumnTempExt,
        TextBoxColumnTempExt,
        TokenBoxColumnTempExt,
        ComboBoxColumnTempExt,
        SetFilterRowData,
        DepUserSelectPopupExt,
        QueryBuilderExt,
        ValueFunPopupExt,
        QYCreateCtrlEle,
        QYCreateGroupEle,
        QYSetCaptionEle,
        QYDiagram,
        FlowExecObj,
        SubmitNode,
    } = {};

    var miniAdmin = {

        /**
         * 后台框架初始化
         * @param options.iniUrl   后台初始化接口地址
         * @param options.clearUrl   后台清理缓存接口
         * @param options.urlHashLocation URL地址hash定位
         * @param options.bgColorDefault 默认皮肤
         * @param options.multiModule 是否开启多模块
         * @param options.menuChildOpen 是否展开子菜单
         * @param options.loadingTime 初始化加载时间
         * @param options.pageAnim iframe窗口动画
         * @param options.maxTabNum 最大的tab打开数量
         */
        render: function (options) {

            ({
                //QD
                GetWebApiInfo,
                GetFormDataApiInfo,
                GetFormDataCondition,
                QDFitlerToEj2,
                Ej2ToQDFilter,
                QDFilterToEj2Rule,
                Ej2RuleToQDFilter,
                Ej2PredicateToEj2Rule,
                GetFormDataOrder,
                GetRequestTableObj,
                SetChildTableFilterValue,
                SetTableFilterValue,
                GetDataManagerObj,
                GetDataManagerByDataTable,
                GetTableRequestComplete,
                GetDataByDataTable,
                ExecRequest,
                Adaptor,
                //QC
                SysLogin,
                LoginOut,
                RecordMyUserInfo,
                isEmptyObject,
                StringTrim,
                GetNewGUID,
                GetQueryString,
                ReturnPortalCenter,
                GetFormFilePath,
                GridAutoSize,
                EditScreenShotPage,
                //comm
                CheckboxList,
                ALink,
                QYCardView,
                QYIconSelector,
                BindFormCtrl,
                LayoutGroupBind,
                CascadingChildCtrl,
                QYCtrlBind,
                UploadPopupExt,
                UploadSetCustomPath,
                ToSelectFilesAction,
                SysUploadFileSelected,
                FileUpload,
                FileDelete,
                FileDownload,
                CreateFolder,
                FileCopy,
                FileMove,
                FileRename,
                FileView,
                //pagebind
                FormInit,
                GetFormDataApiUrl,
                GetGridColumnEditParam,
                SysSelectDataBind,
                GridBind,
                CtrlBind,
                LocaDataBind,
                SetFromDataCurrentRow,
                SetFromDataCurrentRowBayKeyValue,
                SetFromDataSelectRow,
                SetFromDataSelectRowByKeyValue,
                GetFormChildDataObj,
                SaveAllData,
                BatchSave,
                SysAppend,
                ReplaceDisplayClass,
                GetFormFunData,
                GetUserShowFun,
                GetUserEditFun,
                SetGridFun,
                GridRowSelecting,
                GridQueryCellInfo,
                GridBeforeBatchAdd,
                GridBeginEdit,
                ValidateData,
                CreateSysGridToolbarTemp,
                GridImportFile,
                GetGridImportParam,
                ShowTempEditPopup,
                HideTempEditPopup,
                SetTreeViewSelectNode,
                StartFlow,
                RevokeFlow,
                ReturnFlow,
                EndFlow,
                AddFlowReceiveUser,
                GetFlowCandidate,
                GetDataSource,
                OpenIconLibrary,
                //ctrl
                PanelExt,
                GridViewExt,
                FormLayoutExt,
                QYLabel,
                QYSpinEdit,
                QYColorEdit,
                QYPopup,
                QYTabGroup,
                QYBadge,
                QYCustomFilter,
                QYFileView,
                QYFileManager,
                replaceIllegalCharactersWithFullWidth,
                BtnTextBoxColumnTempExt,
                CheckBoxListTempExt,
                ColorEditColumnTempExt,
                SpinEditColumnTempExt,
                DropDownTreeColumnTempExt,
                HyperLinkColumnTempExt,
                ImageColumnTempExt,
                TextBoxColumnTempExt,
                TokenBoxColumnTempExt,
                ComboBoxColumnTempExt,
                SetFilterRowData,
                DepUserSelectPopupExt,
                QueryBuilderExt,
                ValueFunPopupExt,
                QYCreateCtrlEle,
                QYCreateGroupEle,
                QYSetCaptionEle,
                QYDiagram,
                FlowExecObj,
                SubmitNode,
            } = options.QyCtrl);

            options.iniUrl = options.iniUrl || null;
            options.clearUrl = options.clearUrl || null;
            options.urlHashLocation = options.urlHashLocation || false;
            options.bgColorDefault = options.bgColorDefault || 12;
            options.multiModule = options.multiModule || false;
            options.menuChildOpen = options.menuChildOpen || false;
            options.loadingTime = options.loadingTime || 1;
            options.pageAnim = options.pageAnim || false;
            options.maxTabNum = options.maxTabNum || 20;
            options.firstItemsLocation = options.firstItemsLocation || "Top";
            this.options = options;

            //$.getJSON(options.iniUrl, function (data) {
            //后续将接口添加到外部服务接口管理，然后数据源添加接口模型，导航绑定数据源
            ExecRequest(options.iniUrl, "GET", null, (jsonData) => {
                var data = null;
                if (jsonData.Type == "success") {
                    data = jsonData.Result;
                }
                if (data == null) {
                    miniAdmin.error('暂无菜单信息')
                } else {
                    miniAdmin.renderLogo(options.logoInfo);// (data.logoInfo);
                    miniAdmin.renderClear(options.clearUrl);
                    miniAdmin.renderAnim(options.pageAnim);
                    miniAdmin.renderUser();
                    miniAdmin.listen();

                    miniAdmin.headerMenus = data.TopMenus;
                    miniAdmin.leftMenus = data.LeftMenus;
                    miniAdmin.dataMenuList = data.RightMenus;
                    miniAdmin.dataMenuRelation = data.Relations;
                    miniAdmin.sysParamsString = options.sysParamsString;
                    miniAdmin.maxTabNum = options.maxTabNum;
                    miniAdmin.dataMenuSelected = [];


                    //miniTab.menuList = data.menuInfo;
                    //miniTab.dataMenuList = data.dataMenuInfo;
                    //miniTab.dataMenuRelation = data.relationInfo;
                    //miniTab.sysParamsString = options.sysParamsString;
                    //miniTab.dataMenuSelected = [];


                    if ((miniAdmin.dataMenuList && miniAdmin.dataMenuList.length > 0) || !options.homeInfo.href) {
                        // 找到要移除的元素
                        var homeContentEle = document.getElementById("layuiminiHomeTabIframe");
                        var homeTitleEle = document.getElementById("layuiminiHomeTabId");
                        // 移除元素
                        homeContentEle.remove();
                        homeTitleEle.remove();
                    } else {
                        miniAdmin.renderHome(options.homeInfo);// (data.homeInfo);
                    }
                    miniMenu.render({
                        menuList: miniAdmin.headerMenus,
                        leftMenuList: miniAdmin.leftMenus,
                        multiModule: options.multiModule,
                        menuChildOpen: options.menuChildOpen,
                        dataMenuList: miniAdmin.dataMenuList,
                        QyCtrl: options.QyCtrl,
                        firstItemsLocation: options.firstItemsLocation,
                        logoInfo: options.logoInfo,
                    });
                    miniTab.render({
                        filter: 'layuiminiTab',
                        urlHashLocation: options.urlHashLocation,
                        multiModule: options.multiModule,
                        menuChildOpen: options.menuChildOpen,
                        maxTabNum: options.maxTabNum,
                        menuList: miniAdmin.leftMenus,
                        headMenuList: miniAdmin.headerMenus,
                        homeInfo: options.homeInfo,
                        listenSwichCallback: function () {
                            miniAdmin.renderDevice();
                        },
                    });
                    miniTheme.render({
                        bgColorDefault: options.bgColorDefault,
                        listen: true,
                    });
                    miniAdmin.deleteLoader(options.loadingTime);
                }
            });
            //.fail(function () {
            //    miniAdmin.error('菜单接口有误');
            //});
        },

        /**
         * 初始化logo
         * @param data
         */
        renderLogo: function (data) {
            data.href = `${window.location.origin}${(!data.href || data.href.startsWith("/") ? data.href : `/${data.href}`)}`;
            var html = '<a href="' + data.href + '"><img src="' + data.image + '" alt="logo"><h1>' + data.title + '</h1></a>';
            if (!data.image) {
                html = '<a href="' + data.href + '"><h1>' + data.title + '</h1></a>';
            } else {
                html = '<a href="' + data.href + '"><img src="' + data.image + '" alt="logo"></a>';
            }
            $('.layuimini-logo').html(html);
        },

        getItemById: function (tabId) {
            if (!tabId) return null;
            let selItem = this.headerMenus.find(x => x.id == tabId);
            if (!selItem) {
                //selItem = this.leftMenus.find(x => x.id == tabId);
                //改为递归获取
                selItem = getLeftMenu(this.leftMenus, tabId);

                function getLeftMenu(items, targetId) {
                    for (const obj of items) {
                        if (obj.id === targetId) {
                            return obj;
                        }
                        if (obj.items && obj.items.length) {
                            const found = getLeftMenu(obj.items, targetId);
                            if (found) {
                                return found;
                            }
                        }
                    }
                    return null; // 没找到返回null
                }
            }
            return selItem;
        },


        showFloatingActionButtons: function (tabId) {
            let selItem = this.getItemById(tabId);
            if (selItem && selItem.status != "operation") {
                if (!this.hasFloatBtns) {
                    layui.use(function () {
                        var util = layui.util;
                        // 自定义固定条
                        util.fixbar({
                            //bars: [{ // 定义可显示的 bar 列表信息 -- v2.8.0 新增
                            //    type: 'share',
                            //    icon: 'layui-icon-share'
                            //}, {
                            //    type: 'help',
                            //    icon: 'layui-icon-help'
                            //}, {
                            //    type: 'cart',
                            //    icon: 'layui-icon-cart',
                            //    style: 'background-color: #FF5722;'
                            //}, {
                            //    type: 'groups',
                            //    content: '群',
                            //    style: 'font-size: 21px;'
                            //}],
                            // bar1: true,
                            // bar2: true,
                            // default: false, // 是否显示默认的 bar 列表 --  v2.8.0 新增
                            // bgcolor: '#393D52', // bar 的默认背景色
                            // css: {right: 100, bottom: 100},
                            // target: '#target-test', // 插入 fixbar 节点的目标元素选择器
                            // duration: 300, // top bar 等动画时长（毫秒）
                            bars: [
                                {
                                    type: '应用权限',
                                    icon: 'layui-icon  layui-icon-lock',
                                },
                                {
                                    type: '解除权限',
                                    icon: 'layui-icon  layui-icon-key',
                                },
                                {
                                    type: '运行页面',
                                    icon: 'layui-icon  layui-icon-ie',
                                },
                                {
                                    type: '功能设计',
                                    icon: 'layui-icon  layui-icon-vercode',
                                },
                                {
                                    type: '表单设计',
                                    icon: 'layui-icon  layui-icon-layer',
                                },
                                {
                                    type: '功能描述',
                                    icon: 'layui-icon  layui-icon-read',
                                },
                                {
                                    type: '原型描述',
                                    icon: 'layui-icon  layui-icon-fonts-html',
                                },],
                            on: { // 任意事件 --  v2.8.0 新增
                                mouseenter: function (type) {
                                    layer.tips(type, this, {
                                        tips: 4,
                                        fixed: true
                                    });
                                },
                                mouseleave: function (type) {
                                    layer.closeAll('tips');
                                }
                            },
                            // 点击事件
                            click: function (type) {
                                //console.log(this, type);
                                // layer.msg(type);
                                let selId = window.document.querySelector(".layuimini-tab .layui-tab-title li.layui-this").getAttribute("lay-id");
                                let selItem = layui.miniAdmin.getItemById(selId);
                                let tabDiv = document.getElementById(`layminiIframe_${selId}`);
                                if (!selItem) {
                                    alert("功能未找到!");
                                    return;
                                }
                                if (type === "应用权限" || type === "解除权限") {
                                    tabDiv.innerHTML = "";
                                    let authSessionKey = `authViewSet_${selItem.conId}`;
                                    let authSessionVal = "apply";//应用前端权限控制
                                    if (type === "解除权限") {
                                        authSessionVal = "free";//不应用前端权限控制
                                    }
                                    sessionStorage.setItem(authSessionKey, authSessionVal);
                                    let pageInfo = layui.miniAdmin.GetNavPageJsUrlAndParams(selItem.NavigationUrl, selItem.id);
                                    QB.loadModule(tabDiv, pageInfo.url, pageInfo.params);
                                } else if (type === "功能设计") {
                                    let funUrl = QB.GetEntFullPath(`/DataCenter/AppManagement/content/功能设置.html?flownodeid=166CD530238344C2813D50F4D162389D&checkid=${selItem.id}&sysid=${selItem.SysId}&modid=${selItem.SysId}`);

                                    window.open(funUrl);
                                } else if (type === "表单设计") {
                                    let pageUrl = QB.GetEntFullPath("/DataCenter/AppManagement/content/form/Designer/Main.html?formkey=" + selItem.conId);

                                    window.open(pageUrl);
                                } else if (type === "功能描述") {
                                    tabDiv.innerHTML = "";
                                    let pageParams = [{ key: "navid", value: selId }, { key: "text", value: "功能" }]
                                    let pageUrl = window.location.origin + "/SysForm/PrototypePreview.page.js";
                                    QB.loadModule(tabDiv, pageUrl, pageParams);
                                } else if (type === "原型描述") {
                                    tabDiv.innerHTML = "";
                                    let pageParams = [{ key: "navid", value: selId }, { key: "text", value: "原型" }]
                                    let pageUrl = window.location.origin + "/SysForm/PrototypePreview.page.js";
                                    QB.loadModule(tabDiv, pageUrl, pageParams);
                                } else if (type === "运行页面") {
                                    tabDiv.innerHTML = "";

                                    let pageInfo = layui.miniAdmin.GetNavPageJsUrlAndParams(selItem.NavigationUrl, selItem.id);
                                    QB.loadModule(tabDiv, pageInfo.url, pageInfo.params).then(() => {
                                        layui.miniAdmin.showFloatingActionButtons(selId);
                                    }).catch((err) => {
                                        //console.log(err);
                                        if (err === "404") {
                                            layui.miniAdmin.showFloatingActionButtons(selId);
                                            //如果页面文件不存在，加载预览原型页面
                                            let pageParams = [{ key: "navid", value: selId }, { key: "text", value: "原型" }]
                                            let pageUrl = window.location.origin + "/SysForm/PrototypePreview.page.js";
                                            QB.loadModule(tabDiv, pageUrl, pageParams);
                                        }
                                    });
                                }
                            }
                        });
                    });

                    this.hasFloatBtns = true;
                }
                let fixBar = window.document.querySelector(".layui-fixbar");
                if (fixBar) {
                    fixBar.style.display = "block";
                }
            } else {
                let fixBar = window.document.querySelector(".layui-fixbar");
                if (fixBar) {
                    fixBar.style.display = "none";
                }
            }
        },

        /**
         * 初始化首页
         * @param data
         */
        renderHome: function (data) {
            sessionStorage.setItem('layuiminiHomeHref', data.href);//<span class="layuimini-tab-active"></span>
            $('#layuiminiHomeTabId').html('<span class="disable-close">' + data.title + '</span><i class="layui-icon layui-unselect layui-tab-close">ဆ</i>');
            $('#layuiminiHomeTabId').attr('lay-id', data.href);
            if (data.href && data.href.startsWith("http")) {
                $('#layuiminiHomeTabIframe').html('<iframe width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0"  src="' + data.href + '"></iframe>');
            } else {
                $('#layuiminiHomeTabIframe').html('<div class="qyformdiv" width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0" "></iframe>');
                let tabDiv = document.getElementById(`layuiminiHomeTabIframe`).querySelector(".qyformdiv");
                var pageInfo = this.GetNavPageJsUrlAndParams(data.href, "");
                QB.loadModule(tabDiv, pageInfo.url, pageInfo.params).then(() => { }).catch((err) => {
                    console.log(err);
                    //如果页面文件不存在，加载预览原型页面
                    //let pageParams = [{ key: "navid", value: options.tabId }]
                    //let pageUrl = window.location.origin + "/SysForm/PrototypePreview.page.js";
                    //QB.loadModule(tabDiv, pageUrl, pageParams);
                });
            }
        },


        renderFirstPage: function () {
            //有首页直接返回
            var homeTitleEle = document.getElementById("layuiminiHomeTabId");
            if (homeTitleEle) return;

            var loading = layer.load(0, { shade: false, time: 2 * 1000 });

            var tabId = "";
            href = "";
            title = "";
            target = "";
            //先找左侧
            var selectItem = document.querySelector(".layui-nav-tree .layui-this a");
            if (selectItem) {
                tabId = selectItem.getAttribute('id');
                href = selectItem.getAttribute('layuimini-href');
                title = selectItem.textContent;
                target = selectItem.getAttribute('target');
            } else {
                //找头部
                selectItem = document.querySelector(".layuimini-header-menu .layui-nav-item.layui-this");

                tabId = selectItem.getAttribute("data-menu");
                var firstItem = miniAdmin.headerMenus.find(x => x.id == tabId);
                href = firstItem.NavigationUrl;
                title = firstItem.text;
            }


            var el = $("[id='" + tabId + "']", ".layuimini-menu-left");//$("[layuimini-href='" + tabId + "']", ".layuimini-menu-left");
            layer.close(window.openTips);
            if (el.length) {
                $(el).closest(".layui-nav-tree").find(".layui-this").removeClass("layui-this");
                $(el).parent().addClass("layui-this");
            }


            if (window.location.hash) return;

            if (target === '_blank') {
                layer.close(loading);
                window.open(href, "_blank");
                return false;
            }

            if (tabId === null || tabId === undefined) tabId = new Date().getTime();
            var checkTab = miniTab.check(tabId);
            if (!checkTab) {
                miniTab.create({
                    tabId: tabId,
                    href: href,
                    title: title,
                    isIframe: false,
                    maxTabNum: layui.miniAdmin.options.maxTabNum,
                });
            }
            element.tabChange('layuiminiTab', tabId);
            layer.close(loading);
        },

        /**
         * 渲染用户信息
         */
        renderUser: function () {
            var user = null;
            if (typeof QB.GetUserInfo == "function") {
                user = QB.GetUserInfo();
            }
            var userSelEl = $(".layuimini-setting")[0];
            if (user) {
                userSelEl.children[0].innerText = user.UserName;
            } else {
                userSelEl.children[0].innerText = "";
            }
        },

        /**
         * 初始化缓存地址
         * @param clearUrl
         */
        renderClear: function (clearUrl) {
            $('.layuimini-clear').attr('data-href', clearUrl);
        },

        /**
         * 初始化iframe窗口动画
         * @param anim
         */
        renderAnim: function (anim) {
            if (anim) {
                $('#layuimini-bg-color').after('<style id="layuimini-page-anim">' +
                    '.layui-tab-item.layui-show {animation:moveTop 1s;-webkit-animation:moveTop 1s;animation-fill-mode:both;-webkit-animation-fill-mode:both;position:relative;height:100%;-webkit-overflow-scrolling:touch;}\n' +
                    '@keyframes moveTop {0% {opacity:0;-webkit-transform:translateY(30px);-ms-transform:translateY(30px);transform:translateY(30px);}\n' +
                    '    100% {opacity:1;-webkit-transform:translateY(0);-ms-transform:translateY(0);transform:translateY(0);}\n' +
                    '}\n' +
                    '@-o-keyframes moveTop {0% {opacity:0;-webkit-transform:translateY(30px);-ms-transform:translateY(30px);transform:translateY(30px);}\n' +
                    '    100% {opacity:1;-webkit-transform:translateY(0);-ms-transform:translateY(0);transform:translateY(0);}\n' +
                    '}\n' +
                    '@-moz-keyframes moveTop {0% {opacity:0;-webkit-transform:translateY(30px);-ms-transform:translateY(30px);transform:translateY(30px);}\n' +
                    '    100% {opacity:1;-webkit-transform:translateY(0);-ms-transform:translateY(0);transform:translateY(0);}\n' +
                    '}\n' +
                    '@-webkit-keyframes moveTop {0% {opacity:0;-webkit-transform:translateY(30px);-ms-transform:translateY(30px);transform:translateY(30px);}\n' +
                    '    100% {opacity:1;-webkit-transform:translateY(0);-ms-transform:translateY(0);transform:translateY(0);}\n' +
                    '}' +
                    '</style>');
            }
        },


        /**
         * 获取导航地址
         * @param {any} NavUrl
         * @returns
         */
        //GetNavMenuUrl: function (NavUrl, itemId) {
        //    //后续根据页面状态跳转不同服务器地址，维护状态仅允许开发商用户访问，维护添加背景水印维护中
        //    var newUrl = NavUrl;
        //    if (newUrl.toLowerCase().startsWith('http')) {
        //        return newUrl;
        //    } else {
        //        newUrl = QB.GetEntFullPath(newUrl);
        //    }
        //    newUrl = newUrl.replace(".aspx", ".html");
        //    if (this.sysParamsString && this.sysParamsString != "") {
        //        var sysParams = this.sysParamsString.split(';');
        //        var sysParamStr = "";
        //        for (var i = 0; i < sysParams.length; i++) {
        //            sysParamStr += `&${sysParams[i]}=${GetQueryString(sysParams[i])}`;
        //        }
        //        if (newUrl.indexOf("?") == -1)
        //            newUrl += `?${sysParamStr.substring(1)}`;
        //        else
        //            newUrl += sysParamStr;
        //    }
        //    //let relDataMenus = this.dataMenuRelation.filter(x => x.childrowid == itemId);
        //    let relDataMenus = this.dataMenuRelation.filter(x => x.childrowid == itemId);
        //    if (relDataMenus.length > 0) {
        //        //分割url，和参数，替换或添加参数
        //        var urlSplit = newUrl.split('?');
        //        var paramArr = urlSplit.length > 1 ? urlSplit[1].split('&') : [];
        //        for (var i = 0; i < relDataMenus.length; i++) {
        //            var relData = relDataMenus[i];
        //            var selData = this.dataMenuSelected.find(x => x.dataMenuId == relData.prowid);
        //            if (selData) {
        //                var paramTextIndex = paramArr.findIndex(x => x.startsWith(relData.TextParamName + "="));
        //                if (paramTextIndex != -1) {
        //                    paramArr[paramTextIndex] = `${relData.TextParamName}=${selData.selectedText}`;
        //                } else {
        //                    paramArr.push(`${relData.TextParamName}=${selData.selectedText}`);
        //                }
        //                var paramValueIndex = paramArr.findIndex(x => x.startsWith(relData.ValParamName + "="));
        //                if (paramValueIndex != -1) {
        //                    paramArr[paramValueIndex] = `${relData.ValParamName}=${selData.selectedValue}`;
        //                } else {
        //                    paramArr.push(`${relData.ValParamName}=${selData.selectedValue}`);
        //                }
        //            }
        //            //newUrl += `&${relData.TextParamName}=${selData.selectedText}&${relData.ValParamName}=${selData.selectedValue}`;
        //        }
        //        newUrl = urlSplit[0] + "?" + paramArr.join('&');
        //    }
        //    return newUrl;
        //},

        getDataMenuParams: function (itemId, params) {
            if (!itemId) return;
            let itemInfo = this.getItemById(itemId);
            if (!itemInfo || !itemInfo.pid)
                return;

            getModelParams(itemInfo.pid, params);
            function getModelParams(pid, params) {

                let parentItem = layui.miniAdmin.getItemById(pid);
                if (!parentItem) {
                    //如果父级不存在，则为顶层，直接获取数据目录关系并设置参数
                    setDMParams(pid, params);
                } else {
                    setDMParams(parentItem.id, params);
                    if (parentItem.pid) {
                        getModelParams(parentItem.pid, params);
                    }
                }
            }

            function setDMParams(pid, params) {
                let relDataMenu = layui.miniAdmin.dataMenuRelation.filter(x => x.prowid === pid);
                if (relDataMenu && relDataMenu.length > 0) {
                    relDataMenu.forEach((relData) => {
                        let selData = layui.miniAdmin.dataMenuSelected.find(x => x.dataMenuId == relData.childrowid);
                        //设置文本参数
                        var paramTextIndex = params.findIndex(x => x.key == relData.TextParamName);
                        if (paramTextIndex != -1) {
                            params[paramTextIndex] = { key: relData.TextParamName, value: selData.selectedText };
                        } else {
                            params.push({ key: relData.TextParamName, value: selData.selectedText });
                        }
                        //设置值参数
                        var paramValueIndex = params.findIndex(x => x.key == relData.ValParamName);
                        if (paramValueIndex != -1) {
                            params[paramValueIndex] = { key: relData.ValParamName, value: selData.selectedValue };
                        } else {
                            params.push({ key: relData.ValParamName, value: selData.selectedValue });
                        }
                    });
                }
            }
        },

        GetNavPageJsUrlAndParams: function (NavUrl, itemId) {

            //后续根据页面状态跳转不同服务器地址，维护状态仅允许开发商用户访问，维护添加背景水印维护中
            let returnObj = QB.GetPageJsUrlAndParams(NavUrl);

            //系统参数
            if (this.sysParamsString && this.sysParamsString != "") {
                var sysParams = this.sysParamsString.split(';');
                for (var i = 0; i < sysParams.length; i++) {
                    returnObj.params.push({ key: sysParams[i], value: GetQueryString(sysParams[i]) });
                }
            }

            //数据目录改为模块绑定关系，模块下所有子项统一使用模块指定的参数
            this.getDataMenuParams(itemId, returnObj.params);


            //数据目录参数
            //var relDataMenus = this.dataMenuRelation.filter(x => x.childrowid == itemId);
            //if (relDataMenus.length > 0) {
            //    for (var i = 0; i < relDataMenus.length; i++) {
            //        var relData = relDataMenus[i];
            //        var selData = this.dataMenuSelected.find(x => x.dataMenuId == relData.prowid);
            //        if (selData) {
            //            var paramTextIndex = returnObj.params.findIndex(x => x.key == relData.TextParamName);
            //            if (paramTextIndex != -1) {
            //                returnObj.params[paramTextIndex] = { key: relData.TextParamName, value: selData.selectedText };
            //            } else {
            //                returnObj.params.push({ key: relData.TextParamName, value: selData.selectedText });
            //            }
            //            var paramValueIndex = returnObj.params.findIndex(x => x.key == relData.ValParamName);
            //            if (paramValueIndex != -1) {
            //                returnObj.params[paramValueIndex] = { key: relData.ValParamName, value: selData.selectedValue };
            //            } else {
            //                returnObj.params.push({ key: relData.ValParamName, value: selData.selectedValue });
            //            }
            //        }
            //    }
            //}

            //功能参数
            let curItem = this.leftMenus.find(x => x.id == itemId);
            if (!curItem) {
                curItem = this.headerMenus.find(x => x.id == itemId);
            }
            if (curItem && curItem.navParams) {
                let navParams = JSON.parse(curItem.navParams);
                returnObj.params.push(navParams);
            }
            return returnObj;
        },

        fullScreen: function () {
            var el = document.documentElement;
            var rfs = el.requestFullScreen || el.webkitRequestFullScreen;
            if (typeof rfs != "undefined" && rfs) {
                rfs.call(el);
            } else if (typeof window.ActiveXObject != "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            } else if (el.msRequestFullscreen) {
                el.msRequestFullscreen();
            } else if (el.oRequestFullscreen) {
                el.oRequestFullscreen();
            } else if (el.webkitRequestFullscreen) {
                el.webkitRequestFullscreen();
            } else if (el.mozRequestFullScreen) {
                el.mozRequestFullScreen();
            } else {
                miniAdmin.error('浏览器不支持全屏调用！');
            }
        },

        /**
         * 退出全屏
         */
        exitFullScreen: function () {
            var el = document;
            var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.exitFullScreen;
            if (typeof cfs != "undefined" && cfs) {
                cfs.call(el);
            } else if (typeof window.ActiveXObject != "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            } else if (el.msExitFullscreen) {
                el.msExitFullscreen();
            } else if (el.oRequestFullscreen) {
                el.oCancelFullScreen();
            } else if (el.mozCancelFullScreen) {
                el.mozCancelFullScreen();
            } else if (el.webkitCancelFullScreen) {
                el.webkitCancelFullScreen();
            } else {
                miniAdmin.error('浏览器不支持全屏调用！');
            }
        },

        /**
         * 初始化设备端
         */
        renderDevice: function () {
            if (miniAdmin.checkMobile()) {
                $('.layuimini-tool i').attr('data-side-fold', 1);
                $('.layuimini-tool i').attr('class', 'fa fa-outdent');
                $('.layui-layout-body').removeClass('layuimini-mini');
                $('.layui-layout-body').addClass('layuimini-all');
            }
        },


        /**
         * 初始化加载时间
         * @param loadingTime
         */
        deleteLoader: function (loadingTime) {
            setTimeout(function () {
                $('.layuimini-loader').fadeOut();
            }, loadingTime * 1000)
        },

        /**
         * 成功
         * @param title
         * @returns {*}
         */
        success: function (title) {
            return layer.msg(title, { icon: 1, shade: this.shade, scrollbar: false, time: 2000, shadeClose: true });
        },

        /**
         * 失败
         * @param title
         * @returns {*}
         */
        error: function (title) {
            return layer.msg(title, { icon: 2, shade: this.shade, scrollbar: false, time: 3000, shadeClose: true });
        },

        /**
         * 判断是否为手机
         * @returns {boolean}
         */
        checkMobile: function () {
            var ua = navigator.userAgent.toLocaleLowerCase();
            var pf = navigator.platform.toLocaleLowerCase();
            var isAndroid = (/android/i).test(ua) || ((/iPhone|iPod|iPad/i).test(ua) && (/linux/i).test(pf))
                || (/ucweb.*linux/i.test(ua));
            var isIOS = (/iPhone|iPod|iPad/i).test(ua) && !isAndroid;
            var isWinPhone = (/Windows Phone|ZuneWP7/i).test(ua);
            var clientWidth = document.documentElement.clientWidth;
            if (!isAndroid && !isIOS && !isWinPhone && clientWidth > 1024) {
                return false;
            } else {
                return true;
            }
        },

        /**
         * 监听
         */
        listen: function () {

            /**
             * 清理
             */
            $('body').on('click', '[data-clear]', function () {
                var loading = layer.load(0, { shade: false, time: 2 * 1000 });
                sessionStorage.clear();

                // 判断是否清理服务端
                var clearUrl = $(this).attr('data-href');
                if (clearUrl != undefined && clearUrl != '' && clearUrl != null) {
                    $.getJSON(clearUrl, function (data, status) {
                        layer.close(loading);
                        if (data.code != 1) {
                            return miniAdmin.error(data.msg);
                        } else {
                            return miniAdmin.success(data.msg);
                        }
                    }).fail(function () {
                        layer.close(loading);
                        return miniAdmin.error('清理缓存接口有误');
                    });
                } else {
                    layer.close(loading);
                    return miniAdmin.success('清除缓存成功');
                }
            });

            /**
             * 刷新
             */
            $('body').on('click', '[data-refresh]', function () {
                $(".layui-tab-item.layui-show").find("iframe")[0].contentWindow.location.reload();
                miniAdmin.success('刷新成功');
            });

            /**
             * 监听提示信息
             */
            $("body").on("mouseenter", ".layui-nav-tree .menu-li", function () {
                if (miniAdmin.checkMobile()) {
                    return false;
                }
                var classInfo = $(this).attr('class'),
                    tips = $(this).prop("innerHTML"),
                    isShow = $('.layuimini-tool i').attr('data-side-fold');
                if (isShow == 0 && tips) {
                    tips = "<ul class='layuimini-menu-left-zoom layui-nav layui-nav-tree layui-this'><li class='layui-nav-item layui-nav-itemed'>" + tips + "</li></ul>";
                    window.openTips = layer.tips(tips, $(this), {
                        tips: [2, '#2f4056'],
                        time: 300000,
                        skin: "popup-tips",
                        success: function (el) {
                            var left = $(el).position().left - 10;
                            $(el).css({ left: left });
                            element.render();
                        }
                    });
                }
            });

            $("body").on("mouseleave", ".popup-tips", function () {
                if (miniAdmin.checkMobile()) {
                    return false;
                }
                var isShow = $('.layuimini-tool i').attr('data-side-fold');
                if (isShow == 0) {
                    try {
                        layer.close(window.openTips);
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            });


            /**
             * 全屏
             */
            $('body').on('click', '[data-check-screen]', function () {
                var check = $(this).attr('data-check-screen');
                if (check == 'full') {
                    miniAdmin.fullScreen();
                    $(this).attr('data-check-screen', 'exit');
                    $(this).html('<i class="fa fa-compress"></i>');
                } else {
                    miniAdmin.exitFullScreen();
                    $(this).attr('data-check-screen', 'full');
                    $(this).html('<i class="fa fa-arrows-alt"></i>');
                }
            });

            /**
             * 点击遮罩层
             */
            $('body').on('click', '.layuimini-make', function () {
                miniAdmin.renderDevice();
            });

        }
    };


    exports("miniAdmin", miniAdmin);
});
